/*
 * Copyright 2023-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package net.yun789.javasipweb.config;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class UdpDecoderHandler extends MessageToMessageDecoder<DatagramPacket> {

    private AtomicInteger msgIndex=new AtomicInteger(0);
    private static final Logger log = LoggerFactory.getLogger(UdpDecoderHandler.class);
    @Override
    protected void decode(ChannelHandlerContext context, DatagramPacket byteBuf, List<Object> list) throws Exception {
        ByteBuf byteBuf1 = byteBuf.content();
        int size = byteBuf1.readableBytes();
        byte[] data = new byte[size];
        byteBuf1.readBytes(data);

        log.info("-------------------------msgIndex--------------------------");


        String fromStr =new String(data) ;
        log.info(fromStr);

        char[] chars = fromStr.toCharArray();
        for(char chr:chars){
//            log.info("chr:"+chr);
        }

        String[] fromList = StringUtils.split(fromStr, '\n');
        String method="";
        Map<String,String> headMap =new HashMap<>();
        for (int i=0;i<fromList.length;i++){
            String curLine=fromList[i];
            if(i==0){
                //请求方法
                method=StringUtils.split(curLine,' ')[0];
                continue;
            }
            if(curLine.equals("\r")){
                break;
            }
            int headIndex=curLine.indexOf(":");
            String headName=curLine.substring(0,headIndex);
            String value=curLine.substring(headIndex+1);
            value= StringUtils.removeEnd(value,"\r");
            value=StringUtils.removeStart(value," ");
            headMap.put(headName,value);

        }


        log.info("headMap:"+headMap);
        String branch="";
        String via = headMap.get("Via");
        if(via.indexOf("branch=")!=-1){
            int indexStart=via.indexOf("branch=");
            branch=via.substring(via.indexOf("branch=")+"branch=".length());
            if(branch.indexOf(";")!=-1){
                branch=branch.substring(0,branch.indexOf(";"));
            }
        }
        String callId=headMap.get("Call-ID");

        String fromTag=getChildrenHeadValue(headMap.get("From"),"tag");

        //回应
        String returnStr="SIP/2.0 200 OK\r\n" +
                "Via: SIP/2.0/UDP 127.0.0.1:5060;rport=5060;branch="+UUID.randomUUID().toString()+"\r\n" +
                "From: \"18954330913\"<sip:18954330913@127.0.0.1:5060>;tag=705514613\r\n" +
                "To: \"18954330913\"<sip:18954330913@127.0.0.1:5060>;tag=705514612\r\n" +
                "Call-ID: "+ UUID.randomUUID().toString() +"\r\n" +
                "CSeq: 2 REGISTER\r\n" +
                "Contact: "+headMap.get("Contact")+"\r\n" +
                "User-Agent: eyeBeam release 1011d stamp 40820\r\n" +
                "Date: "+DateFormatUtils.format(new Date(),"yyyy-MM-dd'T'HH:mm:ss")+"\r\n" +
                "Content-Length: 0\r\n"+
                "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY, PUBLISH, SUBSCRIBE\r\n" +
                "Supported: timer, path, replaces\r\n"+
                "\r\n";

        String returnStr2="SIP/2.0 200 OK\r\n" +
                "Via: SIP/2.0/UDP 127.0.0.1;rport=5060;branch=z9hG4bKQjjap1XKr1cZc\r\n" +
                "Contact: "+headMap.get("Contact").substring(0,headMap.get("Contact").indexOf(";"))+">"+"\r\n" +
                "To: <sip:18954330913@127.0.0.1>;tag=bc06de23\r\n" +
                "From: <sip:18954330913@127.0.0.1>;tag=QX389DN27BvNg\r\n" +
                "Call-ID: "+UUID.randomUUID().toString()+"\r\n" +
                "CSeq: 63034966 NOTIFY\r\n" +
                "User-Agent: eyeBeam release 1011d stamp 40820\r\n" +
                "Content-Length: 0\r\n"
                +"\r\n";

        log.info(returnStr);

        context.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                returnStr, CharsetUtil.US_ASCII), byteBuf.sender()));

    }

    private String getChildrenHeadValue(String headValue,String key){
        if(headValue.indexOf(key+"=")!=-1){
            int indexStart=headValue.indexOf(key+"=");
         String    branch=headValue.substring(indexStart+(key+"=").length());
            if(branch.indexOf(";")!=-1){
                branch=branch.substring(0,branch.indexOf(";"));
            }

            return branch;
        }
        return null;
    }
}